package us.codecraft.webmagic.model;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.time.DateFormatUtils;

import com.Ostermiller.util.CSVPrint;
import com.Ostermiller.util.CSVPrinter;

import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.PageModelPipeline;

public class AntPageModelPipeline implements PageModelPipeline<Object> {

    private CSVPrint csvPrint;

    @Override
    public synchronized void process(Object o, Task task) {
        if (o instanceof AntDetail) {
            System.out.println(ToStringBuilder.reflectionToString(o));
            if (csvPrint == null) {
                try {
                    csvPrint = new CSVPrinter(
                            new FileWriter("e:/" + DateFormatUtils.format(new Date(), "yyyyMMdd") + ".csv", true));
                    csvPrint.writeln(new String[] { "id", "icon", "bg", "title", "subtitle", "packname", "downnum",
                            "tag", "size", "code", "version", "uptime", "desc", "score", "downurl", "reurl", "reurl2",
                            "contentLength", "md5v", "bigRecPic", "menuName", "menuId", "menuPic" });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                AntDetail ant = (AntDetail) o;
                csvPrint.writeln(new String[] { ant.getId(), ant.getIcon(), ant.getBg(), ant.getTitle(),
                        ant.getSubtitle(), ant.getPackname(), ant.getDownnum(), String.join("|", ant.getTag()),
                        ant.getSize(), ant.getCode(), ant.getVersion(), ant.getUptime(), ant.getDesc(), ant.getScore(),
                        ant.getDownurl(), ant.getReurl(), ant.getReurl2(), ant.getContentLength(), ant.getMd5v(),
                        String.join("|", ant.getBigRecPic()), ant.getMenuName(), ant.getMenuId(), ant.getMenuPic() });
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
